<template>
    <!-- 策略挖掘样本集 -->
    <div class="model-manage">
        <div class="mm-panel-wrapper-left">
            <Tree ref="leftTreeRef" :isOwnAccount="true" :topAdd="true" :topAddMenu="right_menuList.rightMenuList_12"
                :folderMenu="right_menuList.rightMenuList_13" :fileMenu="right_menuList.rightMenuList_14"
                :treeData="ownTreeData" :currentNodeKey="currentNodeKey" :defaultExpandedKeys="defaultExpandedKeys"
                @handleAddNode="handleAddModel" @addOrUpdateFolder="handleAddOrUpdateFolder" @nodeClick="nodeClick"
                @nodeDelete="handleNodeDelete" @moveNodeOrder="moveNodeOrder" @handleMenuClick="handleMenuClick">
            </Tree>
        </div>
        <div class="mm-divider"></div>
        <div class="mm-panel-wrapper-right">
            <div class="padding20">

                <div class="mm-panel-title mb-10">
                    数据集基本信息
                    <el-button style="float: right;" class="ml-10" type="primary" @click="handleSave">保存</el-button>
                </div>
                <el-form ref="form" :model="itemForm" :rules="rules" label-width="150px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="itemForm.name"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="样本大小（M）" prop="fileSize">
                                <el-input v-model="itemForm.fileSize"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="创建日期" prop="createTime">
                                <el-date-picker v-model="itemForm.createTime" type="date" placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="样本数量" prop="fileCount">
                                <el-input v-model="itemForm.fileCount"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="描述" prop="description">
                        <el-input type="textarea" v-model="itemForm.description"></el-input>
                    </el-form-item>
                </el-form>
                <div class="mm-panel-title mb-10">
                    样本集信息列表
                    <el-button v-if="isOrigin" style="float: right;" class="ml-10" type="primary"
                        @click="handleConnection">引接</el-button>
                    <el-button v-else style="float: right;" class="ml-10" type="primary"
                        @click="handleSon">子集在线构建</el-button>
                </div>
                <el-table v-loading="loading" :data="tableData" height="280" stripe>
                    <el-table-column label="序号" type="index" width="50" align="center">
                        <template slot-scope="scope">
                            <span>{{
                                (queryParams.pageNum - 1) * queryParams.pageSize +
                                scope.$index +
                                1
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true" />
                    <el-table-column label="样本大小（M）" align="center" prop="fileSize" :show-overflow-tooltip="true"
                        width="120" />
                    <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
                    <el-table-column label="操作" align="center" width="350" class-name="small-padding fixed-width">
                        <template #default="{ row }">
                            <el-button v-show="isOrigin" class="ml-10" type="primary"
                                @click="vscodeOnline(row)">vscode在线标注</el-button>
                            <el-button class="ml-10" type="primary" @click="handleDownload(row)">下载</el-button>
                            <el-button class="ml-10" type="primary" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="flex" style="height: calc(100% - 500px);margin-top: 10px;">
                    <div class="w50">
                        <div class="mm-panel-title mb-10">
                            样本集质量评估结果
                            <el-button v-show="isOrigin" style="float: right;" class="ml-10" type="primary"
                                @click="handleEvaluation">评估</el-button>
                        </div>
                        <div ref="echarts1" id="echarts1"></div>
                    </div>
                    <div class="w50">
                        <div class="mm-panel-title mb-10">
                            样本集统计结果
                            <el-button v-show="isOrigin" style="float: right;" class="ml-10" type="primary"
                                @click="handleStatistics">统计</el-button>
                        </div>
                        <div ref="echarts2" id="echarts2"></div>
                    </div>
                </div>
            </div>
        </div>
        <el-dialog title="数据引接" :visible.sync="openDialog" width="500px" append-to-body>
            <div>
                <div class="mm-panel-title mb-10">
                    已上传文件路径:
                    <el-button style="float: right;" type="primary" @click="uploadFile">上传</el-button>
                </div>
                <div v-if="itemForm.storagePath" class="mt-10">
                    <span style="color: #1890ff;margin-bottom: 20px;">{{ itemForm.storagePath }}</span>
                </div>
                <div v-else class="mt-10" style="color: #999">尚未上传文件</div>
            </div>
            <div slot="footer">
                <el-button type="primary" @click="handleConnectionSubmit">确定</el-button>
                <el-button @click="openDialog = false">取消</el-button>
            </div>
        </el-dialog>
        <AddOrUpdateFolder v-if="isAddOrUpdateFolder" :sampleSetType="3" ref="addOrUpdateFolderRef" @refresh="getList"></AddOrUpdateFolder>
        <AddOrUpdateModel v-if="isAddOrUpdateModel" :sampleSetType="3" ref="addOrUpdateModelRef" @refresh="getList"></AddOrUpdateModel>
    </div>
</template>

<script>
import * as echarts from "echarts"; // 引入 echarts
import { getToken } from "@/utils/auth";
import { mapState } from "vuex";
import {
    getSampleTreeApi,
    addSampleTreeApi,
    deleteSampleTreeApi,
    editSampleTreeApi,
    moveSampleTreeApi,
    getPerceptionSampleApi,
    getPerceptionSampleDetailsApi,
    addPerceptionSampleApi,
    deletePerceptionSampleApi,
    editPerceptionSampleApi,
    downloadPerceptionSampleApi,
} from "@/api/myspace/sampleDataManagement/index";

import Tree from "@/components/LeftTree/tree.vue";
import AddOrUpdateModel from "./components/add-or-update-model.vue";
import AddOrUpdateFolder from "./components/add-or-update-folder.vue";

export default {
    data() {
        return {
            isOrigin: true,
            echartsInstance1: null, // echarts1 实例
            echartsInstance2: null, // echarts2 实例
            itemForm: {
                name: "原始样本集1", //感知样本名称
                fileSize: 300, //感知样本大小
                createTime: "2025-09-01 10:10:10",
                fileCount: 100,
                description: "针对xxx生成的样本数据", //感知描述
                sampleSetId: 1,
                storagePath: ["D:/1.txt", "D:/2.txt"], //感知样本路径
                volumeAddress: "",
                qualityAssessment: "", //质量评估结果
                userId: null,
            },
            rules: {
                name: [{ required: true, message: "名称不可为空", trigger: "blur" }],
            },
            openDialog: false,
            loading: false,
            tableData: [
                {
                    name: "1077819",
                    fileSize: 99,
                    createTime: "2025-09-01 10:10:10",
                    fileCount: 1
                },
                {
                    name: "1077820",
                    fileSize: 100,
                    createTime: "2025-09-01 10:10:10",
                    fileCount: 1
                },
                {
                    name: "1077821",
                    fileSize: 101,
                    createTime: "2025-09-01 10:10:10",
                    fileCount: 1
                },
                {
                    name: "1077822",
                    fileSize: 102,
                    createTime: "2025-09-01 10:10:10",
                    fileCount: 1
                },
                {
                    name: "1077823",
                    fileSize: 103,
                    createTime: "2025-09-01 10:10:10",
                    fileCount: 1
                }
            ],
            queryParams: {
                // 查询参数
                pageNum: 1,
                pageSize: 10,
                name: "",
                modelId: "",
                folderId: "",
            },
            isAddOrUpdateModel: false, // 是否打开新增数据模型弹框
            isAddOrUpdateFolder: false, // 是否打开创建目录的弹框
            isFolder: false, // 是否展示文件夹详情
            isFile: false, // 是否展示文件详情
            isModel: false, //是否是模型详情
            isModelGroupDetail: false, // 是否展示模型组详情,
            selectedNodeInfo: {}, // 当前选中节点的信息
            ownTreeData: [], // 本账户模型列表
            currentNodeKey: 0, // 当前选中节点的key
            defaultExpandedKeys: [], // 默认展开的节点
            editingRow: null, // 存储正在编辑的行数据
        };
    },
    components: {
        Tree,
        AddOrUpdateModel,
        AddOrUpdateFolder,
    },
    computed: {
        ...mapState({
            right_menuList: (state) => state.modelManageTool.right_menuList,
            selectedNodeId: (state) => state.modelManageTool.model.selectedNodeId,
            expandedNodeIds: (state) => state.modelManageTool.model.expandedNodeIds,
            userId: (state) => state.user.id,
        }),
    },
    async created() {
        await this.getList();
        this.currentNodeKey = this.selectedNodeId;
        this.defaultExpandedKeys = this.expandedNodeIds;
        this.$nextTick(() => {
            this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey);
            const params = {
                sampleSetId: this.currentNodeKey,
            };
            // this.getTableData(params);
        });
    },
    mounted() {
        this.$nextTick(() => {
            this.initCharts(); // 初始化图表
        });
        // 上传文件组件
        this.$EventBus.$on("fileSuccess", (response) => {
            if (response.code != 200) {
                this.$message.error(response.msg);
                return;
            }
            this.$message.success("上传成功");
            this.itemForm.storagePath = response.data.filePath;
            this.itemForm.fileSize = response.data.fileSize;
        });
    },
    // 组件销毁时释放图表资源
    beforeDestroy() {
        if (this.echartsInstance1) {
            this.echartsInstance1.dispose();
        }
        if (this.echartsInstance2) {
            this.echartsInstance2.dispose();
        }
    },
    methods: {
        // 子集在线构建
        handleSon() {

        },
        // 保存引接
        handleConnectionSubmit() {
            this.openDialog = false
        },
        uploadFile() {
            this.$EventBus.$emit("openUploader", {
                token: getToken(),
                prefixFlag: 3,
                userId: this.$store.state.user.id,
            });
        },
        // 初始化图表
        initCharts() {
            // 初始化第一个图表
            if (this.$refs.echarts1) {
                this.echartsInstance1 = echarts.init(this.$refs.echarts1);
                this.setChart1Options();
            }

            // 初始化第二个图表
            if (this.$refs.echarts2) {
                this.echartsInstance2 = echarts.init(this.$refs.echarts2);
                this.setChart2Options();
            }
        },
        // 设置第一个图表选项（样本集信息列表）
        setChart1Options() {
            // 定义渐变色
            const barGradient = {
                type: 'linear',
                x: 0, y: 0,
                x2: 0, y2: 1,
                colorStops: [
                    { offset: 0, color: '#195784' }, // 深蓝
                    { offset: 1, color: '#66ccff' }  // 浅蓝
                ]
            };

            const option = {
                tooltip: {},
                xAxis: {
                    type: 'category',
                    data: ['样本1', '样本2', '样本3', '样本4', '样本5', '样本6']
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '数量',
                        type: 'bar',
                        barWidth: '25%', // 设置柱体宽度为25%
                        itemStyle: {
                            color: barGradient // 应用渐变色
                        },
                        data: [10, 25, 18, 32, 15, 30]
                    }
                ]
            };

            this.echartsInstance1.setOption(option);
        },

        // 设置第二个图表选项（样本集统计结果）
        setChart2Options() {
            // 定义渐变色
            const barGradient = {
                type: 'linear',
                x: 0, y: 0,
                x2: 0, y2: 1,
                colorStops: [
                    { offset: 0, color: '#006eff' }, // 深蓝
                    { offset: 1, color: '#83b8ff' }  // 浅蓝
                ]
            };

            const option = {
                tooltip: {},
                xAxis: {
                    type: 'category',
                    data: ['类别A', '类别B', '类别C', '类别D', '类别E', '类别F']
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '统计值',
                        type: 'bar',
                        barWidth: '25%', // 设置柱体宽度为25%
                        itemStyle: {
                            color: barGradient // 应用渐变色
                        },
                        data: [8, 20, 15, 28, 12, 10]
                    }
                ]
            };

            this.echartsInstance2.setOption(option);
        },

        // 响应窗口大小变化
        handleResize() {
            if (this.echartsInstance1) {
                this.echartsInstance1.resize();
            }
            if (this.echartsInstance2) {
                this.echartsInstance2.resize();
            }
        },

        // 评估按钮点击事件
        handleEvaluation() {
            // 这里可以重新加载或更新第一个图表的数据
            console.log("执行评估操作");
            // 示例：更新数据
            // this.echartsInstance1.setOption({
            //   series: [{
            //     data: [12, 28, 20, 35, 18]
            //   }]
            // });
        },

        // 统计按钮点击事件
        handleStatistics() {
            // 这里可以重新加载或更新第二个图表的数据
            console.log("执行统计操作");
            // 示例：更新数据
            // this.echartsInstance2.setOption({
            //   series: [{
            //     data: [10, 22, 18, 30, 14]
            //   }]
            // });
        },
        // 评估
        handleEvaluation() {

        },
        // 统计
        handleStatistics() {

        },
        // 在线编辑vscode
        vscodeOnline(row) {

        },
        // 上传文件组件
        uploadBus() {
            // 模拟用户选择的文件
            // const file = new File(["file content"], "filename.txt", { type: "text/plain" });
            // 打开文件选择框
            this.$EventBus.$emit("openUploader", {
                token: getToken(),
                prefixFlag: 3,
                userId: this.userId,
                // fileObject: file
            });
        },
        // 新增
        handleAdd() {
            this.editingRow = null; // 清空编辑状态
            this.openDialog = true;
        },
        // 保存
        handleSave() {

        },
        // 引接
        handleConnection() {
            console.log("=引接=")
            this.openDialog = true;
        },
        async getList(newNodeId) {
            const params = { sampleSetType: 3 };
            const res = await getSampleTreeApi(params);
            if (res.code == 200 && Array.isArray(res.data)) {
                this.ownTreeData = res.data[0].commonTreeList;
                const targetId = newNodeId || this.selectedNodeId;
                const targetnode = targetId
                    ? this.recurNodeForTarget(this.ownTreeData, targetId)
                    : this.ownTreeData[0];
                this.nodeClick(targetnode);
            }
        },

        // 表格
        async addSubmit(formData) {
            const api = formData.id
                ? editPerceptionSampleApi // 编辑
                : addPerceptionSampleApi; // 新增

            const res = await api(formData);
            if (res.code === 200) {
                this.$message.success(res.msg);
                this.loading = true;
                const params = {
                    sampleSetId: this.currentNodeKey,
                };
                this.getTableData(params);
                this.openDialog = false;
            } else {
                this.openDialog = false;
                this.$message.error(res.msg);
            }
        },
        async getTableData(params) {
            try {
                const res = await getPerceptionSampleApi(params);
                this.tableData = res.rows;
            } catch (error) {
                console.error("获取表格数据失败:", error);
                this.$message.error("数据加载失败，请重试");
            } finally {
                this.loading = false;
            }
        },

        async handleDelete(row) {
            const res = await deletePerceptionSampleApi(row.id);
            if (res.code == 200) {
                this.$message.success(res.msg);
            }
        },

        async handleDownload(row) {
            try {
                const res = await downloadPerceptionSampleApi({ id: row.id });
                const blob = res.data;
                const header = res.headers["content-disposition"];
                const fileName =
                    this.extractFilename(header) || "perception-sample.zip";
                // 下载
                // const blob = new Blob([res], { type: "application/x-zip-compressed" });
                const downloadUrl = URL.createObjectURL(blob);
                const link = document.createElement("a");
                link.href = downloadUrl;
                link.download = fileName;
                link.style.display = "none";
                document.body.appendChild(link);
                link.click();

                document.body.removeChild(link);
                URL.revokeObjectURL(downloadUrl);
            } catch (error) { }
        },

        extractFilename(contentDisposition) {
            if (!contentDisposition) {
                return null;
            }

            // 匹配 filename="xxx" （推荐格式，支持包含空格和特殊字符）
            const filenameMatch = contentDisposition.match(
                /filename\s*=\s*"([^"]+)"/i
            );
            if (filenameMatch) {
                return filenameMatch[1];
            }

            // 匹配 filename=xxx （不带引号的简单格式）
            const filenameSimpleMatch = contentDisposition.match(
                /filename\s*=\s*([^;\s]+)/i
            );
            if (filenameSimpleMatch) {
                return filenameSimpleMatch[1];
            }

            return null;
        },

        // 递归获取当前树节点
        recurNodeForTarget(nodeArr, id) {
            for (let i = 0; i < nodeArr.length; i++) {
                if (nodeArr[i].id == id) {
                    return nodeArr[i];
                } else {
                    if (nodeArr[i].children && nodeArr[i].children.length > 0) {
                        let node = this.recurNodeForTarget(nodeArr[i].children, id);
                        if (node) {
                            return node;
                        }
                    }
                }
            }
        },
        // 新增文件夹
        handleAddOrUpdateFolder(sign, node) {
            this.isAddOrUpdateFolder = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateFolderRef"].init(
                    sign,
                    node,
                    this.ownTreeData,
                    "account"
                );
            });
        },
        // 新增样本集
        handleAddModel(node) {
            this.isAddOrUpdateModel = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateModelRef"].init(undefined, node);
            });
        },
        // 点击树节点，右侧展示详细信息
        nodeClick(node) {
            if (node == undefined) {
                return;
            }
            this.selectedNodeInfo = node;
            this.currentNodeKey = node.id;
            this.$nextTick(() => {
                this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey);
            });
            this.$store.commit("modelManageTool/SET_SELECTED_NODE_ID", {
                moduleName: "model",
                id: node.id,
            });
            if (!node.data) return;

            if (node.type == 0) {
                // 点击的文件夹
                this.isFolder = true;
                this.isModel = false;
                this.$store.commit("modelManageTool/SET_EXPANDED_NODE_IDS", {
                    moduleName: "model",
                    idList: Array.from(new Set([...this.defaultExpandedKeys, node.id])),
                });
            } else {
                // 点击的文件
                this.isFolder = false;
                this.isFile = true;
                this.isModel = true;
            }
        },
        /**
         * 树节点删除事件的回调
         * @param node 被删除的节点
         */
        handleNodeDelete(node) {
            this.$confirm(
                `确定删除${node.type == 0 ? "目录" : "样本集"}  ${node.data.name} ?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    customClass: "message-box-style",
                    type: "warning",
                }
            )
                .then(async () => {
                    const response = await deleteSampleTreeApi(node.id);
                    if (response.code == 200) {
                        this.$message.success(
                            this.$toolHandle.getI18nName(
                                this.$zh.setup.responseText,
                                this.$en.setup.responseText,
                                this.$i18n.locale,
                                "success"
                            )
                        );
                        if (node.id == this.currentNodeKey) {
                            this.isFolder = false;
                            this.isModel = false;
                        }
                        this.getList();
                    }
                })
                .catch(() => { });
        },
        /**
         * 树节点复制事件的回调
         * @param node 被复制的节点
         */
        // handleCopyFile(node) {
        //   addModel({
        //     modelName: node.data.modelName + " Copy",
        //     modelEnglishName: node.data.modelEnglishName + " Copy",
        //     modelAlias: node.data.modelAlias + " Copy",
        //     parentId: node.data.parentId,
        //     nodeType: node.type, // 0表示文件夹，1表示文件
        //     categoryLabel: node.data.categoryLabel,
        //     modelResolution: node.data.modelResolution,
        //     modelDescription: node.data.modelDescription,
        //     modelType: node.data.modelType, // 0表示标准模型，1表示代理模型，2表示数字样机
        //     userId: node.data.userId,
        //   }).then((response) => {
        //     if (response.code == 200) {
        //       this.$message.success(
        //         this.$toolHandle.getI18nName(
        //           this.$zh.setup.responseText,
        //           this.$en.setup.responseText,
        //           this.$i18n.locale,
        //           "success"
        //         )
        //       );
        //       this.getList();
        //     }
        //   });
        // },
        // 移动树节点的顺序
        moveNodeOrder(draggingNode, dropNode, dropType) {
            moveSampleTreeApi({
                movedNodeId: draggingNode.data.id, // 被移动节点的id
                referenceNodeId: dropNode.data.id, // 参照节点的id
                position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
                ancestors: draggingNode.data.data.ancestors, // 祖先
                folderChildrenOrder: {
                    parentId:
                        dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
                    siblingIds:
                        dropType == "inner"
                            ? Array.from(dropNode.childNodes).map((item) => item.data.id)
                            : Array.from(dropNode.parent.childNodes).map(
                                (item) => item.data.id
                            ),
                },
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getList();
                }
            });
        },
        // 点击菜单项触发的事件
        handleMenuClick(menu, node) {
            switch (menu.name) {
                case "新增样本集":
                    this.handleAddModel(node);
                    break;
                case "新增分类":
                    this.handleAddOrUpdateFolder("add");
                    break;
                case "添加子目录":
                    this.handleAddOrUpdateFolder("add", node);
                    break;
                case "编辑":
                    this.handleAddOrUpdateFolder("edit", node);
                    break;
                // case "复制":
                //   // 文件的复制
                //   this.handleCopyFile(node);
                //   break;
                case "删除":
                    // 文件夹/文件的删除
                    this.handleNodeDelete(node);
                    break;
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.model-manage {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;

    .mm-panel-wrapper-left {
        width: 300px;
        height: 100%;
        flex-grow: 0;
        flex-shrink: 0;
        display: flex;
        position: relative;
        padding: 0 10px;
    }

    .mm-divider {
        width: 1px;
        height: auto;
        flex-grow: 0;
        position: relative;
        align-self: stretch;
        background-color: var(--ui-border-color-split);
    }

    .mm-panel-wrapper-right {
        width: 256px;
        height: 100%;
        min-width: 0px;
        flex-grow: 1;
        flex-shrink: 1;
        display: flex;
        position: relative;
        overflow: auto;
    }
}

.padding20 {
    padding: 20px;
    width: 100%;
}

.w50 {
    height: 100%;
    width: 50%;
    padding: 5px;
}

#echarts1,
#echarts2 {
    width: 100%;
    height: calc(100% - 40px); // 减去标题高度
    min-height: 300px;
}

.mm-panel-title {
    height: 26px;
}
</style>
